﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Statistics
{
    public partial class Form1 : Form
    {
        private string selectedFilePath = string.Empty;
        string formattedText = string.Empty;
        //private List<string> wordsList = new List<string>();
        public Form1()
        {

            InitializeComponent();
            button2.Enabled = false;
            button3.Enabled = false;
        }


        //void showFileText(string fileName)
        //{
        //    System.IO.StreamReader sr = new System.IO.StreamReader(fileName,System.Text.Encoding.Default);
        //    string content=sr.ReadToEnd();
        //    sr.Close();
        //    textBox1.Text = content;
        //}



        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "C# files(*.cs)|*.cs";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //showFileText(openFileDialog1.FileName);
                selectedFilePath = openFileDialog1.FileName;
                textBox1.Text = File.ReadAllText(selectedFilePath);

                int originalLineCount = File.ReadLines(selectedFilePath).Count();
                int originalWordCount = Func.CountWords(textBox1.Text);
                MessageBox.Show(originalLineCount.ToString(), "总行数");
                MessageBox.Show(originalWordCount.ToString(), "总单词数");
                button2.Enabled = true;
                button3.Enabled = false;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            // Remove empty lines and comments
            formattedText = Func.Remove(textBox1.Text);

            int formattedLineCount = formattedText.Split('\n').Length;
            int formattedWordCount = Func.CountWords(formattedText);
            textBox1.Text = formattedText;

            MessageBox.Show(formattedLineCount.ToString(), "格式化后总行数");
            MessageBox.Show(formattedWordCount.ToString(), "格式化后总单词数");

            button3.Enabled = true;
        }


        private void button3_Click(object sender, EventArgs e)
        {
            // Count word occurrences
            Dictionary<string, int> wordOccurrences = Func.CountWordOccurrences(formattedText);
            DisplayWordOccurrences(wordOccurrences);
        }
        public void DisplayWordOccurrences(Dictionary<string, int> wordOccurrences)
        {
            listBox1.Items.Clear();
            listBox1.Items.Add("以下是各个单词以及其出现的次数");
            foreach (var kvp in wordOccurrences)
            {
                listBox1.Items.Add($"{kvp.Key}: {kvp.Value}");
            }
        }
    }
}
